<template>
  <div class="notice-list">
    <el-card>
      <template #header>
        <div class="header">
          <span>信息发布管理</span>
          <el-button type="primary" v-if="userType == 9" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            添加信息
          </el-button>
        </div>
      </template>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="标题">
          <el-input v-model="searchForm.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型">
            <el-option label="系统消息" value="0"/>
            <el-option label="用户消息" value="1"/>
            <el-option label="轮播图/广告" value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      
      <el-table :data="notices" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="pushOrg" label="发布内容" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.pushOrg.length > 50 ? scope.row.pushOrg.substring(0, 50) + '...' : scope.row.pushOrg }}
          </template>
        </el-table-column>
        <el-table-column prop="pushTime" label="发布时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.pushTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            {{ formatType(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="icon_path" label="图标" width="100">
          <template #default="scope">
            <el-image v-if="scope.row.icon_path" :src="getIconUrl(scope.row.icon_path)" style="width: 30px; height: 30px;" :preview-src-list="[getIconUrl(scope.row.icon_path)]" />
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="link_url" label="URL链接" :show-overflow-tooltip="true">
          <template #default="scope">
            {{ scope.row.link_url?.length > 50 ? scope.row.link_url?.substring(0, 50) + '...' : scope.row.link_url }}
          </template>
        </el-table-column>
        <el-table-column prop="creator.name" label="创建者" width="100" />
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button type="primary" v-if="userType == 9" text @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 共用对话框：用于新增和编辑 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加信息' : '编辑信息'"
      width="600px"
    >
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="发布内容" prop="pushOrg">
          <el-input v-model="formData.pushOrg" placeholder="请输入发布内容" type="textarea" rows="4"/>
        </el-form-item>
        <el-form-item label="发布时间" prop="pushTime">
          <el-date-picker
            v-model="formData.pushTime"
            type="datetime"
            placeholder="选择日期时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择类型">
            <el-option label="系统消息" value="0"/>
            <el-option label="用户消息" value="1"/>
            <el-option label="轮播图/广告" value="2"/>
          </el-select>
        </el-form-item>
        <el-form-item label="图标">
          <el-upload
            v-model:file-list="iconList"
            class="upload-demo"
            :auto-upload="false"
            :limit="1"
            accept=".jpg,.jpeg,.png"
            :on-change="handleIconChange"
          >
            <el-button type="primary">点击选择图标</el-button>
          </el-upload>
          <el-image v-if="currentIconUrl" :src="currentIconUrl" style="width: 80px; height: 80px; margin-top: 10px;" />
        </el-form-item>
        <el-form-item label="URL链接" prop="link_url">
          <el-input v-model="formData.link_url" placeholder="请输入URL链接"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">{{ submitting ? (dialogType === 'add' ? '上传中...' : '保存中...') : '确定' }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <div>
    <!-- 整个页面的加载状态 -->
    <div v-loading="loading" class="loading-container" element-loading-text="加载中...">
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '../../store/user'
import { STATIC_RESOURCE_URL } from '../../config'
import api from '../../api'

export default {
  name: 'NoticeList',
  components: {
    Plus
  },
  setup() {
    const notices = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const loading = ref(false)
    const submitting = ref(false)
    const userStore = useUserStore()
    
    // 搜索表单
    const searchForm = reactive({
      title: '',
      type: ''
    })
    
    // 对话框状态
    const dialogVisible = ref(false)
    const userType = ref(0)
    const dialogType = ref('add')
    const formRef = ref(null)
    const iconList = ref([])
    
    // 表单数据
    const formData = reactive({
      id: '',
      title: '',
      pushOrg: '',
      pushTime: '',
      type: '',
      icon_path: '',
      link_url: ''
    })
    
    // 当前图标URL
    const currentIconUrl = computed(() => {
      if (iconList.value.length > 0) {
        return URL.createObjectURL(iconList.value[0].raw)
      }
      if (formData.icon_path) {
        return getIconUrl(formData.icon_path)
      }
      return ''
    })
    
    // 表单验证规则
    const formRules = {
      title: [
        { required: true, message: '请输入标题', trigger: 'blur' }
      ],
      pushOrg: [
        { required: true, message: '请输入发布内容', trigger: 'blur' }
      ],
      pushTime: [
        { required: true, message: '请选择发布时间', trigger: 'change' }
      ],
      type: [
        { required: true, message: '请选择类型', trigger: 'change' }
      ]
    }
    
    // 获取图标URL
    const getIconUrl = (iconPath) => {
      // 这里假设后端提供了获取图标的API或静态文件服务
      return `${STATIC_RESOURCE_URL}${iconPath}`
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return ''
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }

    // 格式化类别
    const formatType = (type) =>{
      let showType = ''
      switch(type){
        case 0:
          showType = '系统消息'
          break; 
        case 1:
          showType = '用户消息'
          break; 
        case 2:
          showType = '轮播图/广告'
          break; 
        default:
          showType = '系统消息'
          break; 
      }
      return showType
    }
    
    // 加载通知列表
    const loadNotices = async () => {
      loading.value = true
      userType.value = userStore.user?.category
      try {
        const params = {
          skip: (currentPage.value - 1) * pageSize.value,
          limit: pageSize.value
        }
        
        // 添加搜索条件
        if (searchForm.title) {
          params.title = searchForm.title
        }
        if (searchForm.type !== '') {
          params.type = parseInt(searchForm.type)
        }
        
        const response = await api.get('/chance/notices', {
          params
        })
        notices.value = response
        // 假设后端返回了总数，如果没有，这里可能需要额外的API调用来获取总数
        if (searchForm.title || searchForm.type !== '') {
          // 在实际项目中，这里应该调用一个获取过滤后总数的API
          total.value = Math.min(response.length + (currentPage.value - 1) * pageSize.value, 1000)
        } else {
          // 如果没有搜索条件，可以使用简单的处理
          total.value = response.length + (currentPage.value - 1) * pageSize.value
        }
      } catch (error) {
        ElMessage.error('获取通知列表失败')
      } finally {
        loading.value = false
      }
    }
    
    // 查询
    const handleSearch = () => {
      currentPage.value = 1
      loadNotices()
    }
    
    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      currentPage.value = 1
      loadNotices()
    }
    
    // 添加信息
    const handleAdd = () => {
      dialogType.value = 'add'
      // 重置表单
      if (formRef.value) {
        formRef.value.resetFields()
      }
      // 初始化表单数据
      formData.id = ''
      formData.title = ''
      formData.pushOrg = ''
      formData.pushTime = new Date()
      formData.type = '0'
      formData.icon_path = ''
      formData.link_url = ''
      iconList.value = []
      dialogVisible.value = true
    }
    
    // 编辑信息
    const handleEdit = (row) => {
      dialogType.value = 'edit'
      // 填充表单数据
      formData.id = row.id
      formData.title = row.title
      formData.pushOrg = row.pushOrg
      formData.pushTime = new Date(row.pushTime)
      formData.type = row.type.toString()
      formData.icon_path = row.icon_path || ''
      formData.link_url = row.link_url
      iconList.value = []
      dialogVisible.value = true
    }
    
    // 处理图标选择变化
    const handleIconChange = (file) => {
      // 处理图标文件变化
    }
    
    // 取消操作
    const handleCancel = () => {
      dialogVisible.value = false
      // 清理表单数据
      if (formRef.value) {
        formRef.value.resetFields()
      }
      iconList.value = []
    }
    
    // 提交表单
    const handleSubmit = async () => {
      try {
        submitting.value = true
        await formRef.value.validate(async (valid) => {
          if (valid) {
            try {
                // 数据编辑
                const formDataToSend = new FormData()
                formDataToSend.append('title', formData.title)
                formDataToSend.append('pushOrg', formData.pushOrg)
                formDataToSend.append('pushTime', formData.pushTime.toISOString())
                formDataToSend.append('type', formData.type)
                formDataToSend.append('link_url', formData.link_url)
                
                // 添加图标（如果有）
                if (iconList.value.length > 0) {
                  formDataToSend.append('icon', iconList.value[0].raw)
                }
              if (dialogType.value === 'add') {
                // 添加模式
                await api.post('/chance/notices/', formDataToSend)
                ElMessage.success('信息添加成功')
              } else {
                // 编辑模式
                await api.put(`/chance/notices/${formData.id}`, formDataToSend)
                ElMessage.success('信息编辑成功')
              }
              handleCancel()
              loadNotices()
            } catch (error) {
              ElMessage.error(dialogType.value === 'add' ? '信息添加失败' : '信息编辑失败')
            }
          }
        })
      } finally {
        submitting.value = false
      }
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      pageSize.value = size
      loadNotices()
    }
    
    const handleCurrentChange = (current) => {
      currentPage.value = current
      loadNotices()
    }
    
    // 初始加载
    onMounted(() => {
      loadNotices()
    })
    
    return {
      notices,
      total,
      currentPage,
      pageSize,
      loading,
      submitting,
      searchForm,
      dialogVisible,
      userType,
      dialogType,
      formRef,
      iconList,
      formData,
      formRules,
      currentIconUrl,
      getIconUrl,
      formatDateTime,
      handleSearch,
      resetSearch,
      handleAdd,
      handleEdit,
      handleIconChange,
      handleCancel,
      handleSubmit,
      handleSizeChange,
      formatType,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.notice-list {
  padding: 0;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.upload-demo {
  display: inline-block;
}

.loading-container {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #f9fafb;
  min-height: 200px;
}
</style>